package com.ziki.account.test;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * Exception
     */
    @ExceptionHandler(Exception.class)
    public R exceptionHandle(HttpServletRequest req, Exception e) {
        String msg = StrUtil.sub(StrUtil.isEmpty(e.getMessage()) ? e.toString():e.getMessage(), 0, 256);
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("code", "E001");
        jsonObject.set("message", msg);
        log.error("请求 " + req.getRequestURL() + " 抛出异常： " + e);
        log.error(msg, e);
        return R.builder().code(500).message("异常：" + msg).data(jsonObject).build();
    }

    /**
     * 自定义业务异常
     */
    @ExceptionHandler(CustomException.class)
    public R CustomExceptionHandle(HttpServletRequest req, CustomException e) {
        String msg = StrUtil.sub(StrUtil.isEmpty(e.getMessage()) ? e.toString():e.getMessage(), 0, 256);
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("code", e.getCode());
        jsonObject.set("message", msg);
        log.error("请求 " + req.getRequestURL() + " 抛出异常： " + e);
        log.error(msg, e);
        return R.builder().code(500).message("异常：" + msg).data(jsonObject).build();
    }

    /**
     * 处理业务校验过程中碰到的非法参数异常 该异常基本由{@link org.springframework.util.Assert}抛出
     *
     * @param exception 参数校验异常
     * @return API返回结果对象包装后的错误输出结果
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.OK)
    public R handleIllegalArgumentException(IllegalArgumentException exception) {
        log.error("非法参数,ex = {}", exception.getMessage(), exception);
        return R.failure(exception.getMessage());
    }

    // /**
    //  * AccessDeniedException
    //  * @param e the e
    //  * @return R
    //  */
    // @ExceptionHandler(AccessDeniedException.class)
    // @ResponseStatus(HttpStatus.FORBIDDEN)
    // public R handleAccessDeniedException(AccessDeniedException e) {
    // 	String msg = SpringSecurityMessageSource.getAccessor().getMessage("AbstractAccessDecisionManager.accessDenied",
    // 			e.getMessage());
    // 	log.warn("拒绝授权异常信息 ex={}", msg);
    // 	return R.failure(e.getLocalizedMessage());
    // }

    /**
     * validation Exception
     *
     * @param exception
     * @return R
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleBodyValidException(MethodArgumentNotValidException exception) {
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        log.warn("参数绑定异常,ex = {}", fieldErrors.get(0).getDefaultMessage());
        return R.failure(fieldErrors.get(0).getDefaultMessage());
    }

    /**
     * validation Exception (以form-data形式传参)
     *
     * @param exception
     * @return R
     */
    @ExceptionHandler({BindException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R bindExceptionHandler(BindException exception) {
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        log.warn("参数绑定异常,ex = {}", fieldErrors.get(0).getDefaultMessage());
        return R.failure(fieldErrors.get(0).getDefaultMessage());
    }

}